<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

/**
*
* @package  RealEstateManager
* @copyright 2011 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Rob de Cleen(rob@decleen.com) 
* Homepage: http://www.ordasoft.com
* @version: 2.1 free $
*
**/

$mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path']	= JPATH_SITE;
global $mosConfig_lang; // for 1.6
$mainframe = JFactory::getApplication(); // for 1.6
$GLOBALS['mainframe'] = $mainframe;

if (get_magic_quotes_gpc()) {
  function stripslashes_gpc(&$value)
  {
    $value = stripslashes($value);
  }
  array_walk_recursive($_GET, 'stripslashes_gpc');
  array_walk_recursive($_POST, 'stripslashes_gpc');
  array_walk_recursive($_COOKIE, 'stripslashes_gpc');
  array_walk_recursive($_REQUEST, 'stripslashes_gpc');
}
require_once($mosConfig_absolute_path."/administrator/components/com_realestatemanager/compat.joomla1.5.php");
require_once($mosConfig_absolute_path."/administrator/components/com_realestatemanager/functions.php");
require_once($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.main.categories.class.php");//for 1.6

$lang_def_en=0;
$lang =& JFactory::getLanguage();
foreach ($lang->getLocale() as $locale) {
  $mosConfig_lang=$locale;
  if (file_exists($mosConfig_absolute_path."/components/com_realestatemanager/language/{$mosConfig_lang}.php" ))
  {  
    include_once($mosConfig_absolute_path."/components/com_realestatemanager/language/{$mosConfig_lang}.php" );
    $lang_def_en=1;
    break;
  } 
}
if($lang_def_en!=1)
 {
  $mosConfig_lang = "english";
  include_once($mosConfig_absolute_path."/components/com_realestatemanager/language/english.php" );
 }

/** load the html drawing class */
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.rent.php");
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.html.php");// for 1.6
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.php");// for 1.6
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.rent_request.php");
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.buying_request.php");
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.rent.php");
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.review.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_realestatemanager/admin.realestatemanager.class.others.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_realestatemanager/admin.realestatemanager.class.conf.php");

jimport('joomla.html.pagination');
//include_once($mosConfig_absolute_path.'/libraries/joomla/html/pagination.php');// for 1.6
include_once($mosConfig_absolute_path.'/libraries/joomla/application/pathway.php');// for 1.6




$GLOBALS['realestatemanager_configuration'] = $realestatemanager_configuration;
$my=&JFactory::getUser();
$acl =& JFactory::getACL();
$GLOBALS['my'] =$my;
$GLOBALS['acl'] =$acl;


/*$mainframe->setPageTitle( _REALESTATE_MANAGER_TITLE )*/;
$doc =& JFactory::getDocument(); // for 1.6
$GLOBALS['doc'] = $doc; // for 1.6
$GLOBALS['op'] = $doc; // for 1.6
//$doc->setTitle( _REALESTATE_MANAGER_TITLE ); // for 1.6


if ( !isset($GLOBALS['Itemid']) ) $GLOBALS['Itemid'] = JRequest::getInt( 'Itemid' );
if ( !isset($GLOBALS['Itemid']) )
  $GLOBALS['Itemid'] = $Itemid = intval(mosGetParam( $_REQUEST, 'Itemid', 0 ) );

  $GLOBALS['option'] = 'com_realestatemanager';

$task = trim( mosGetParam( $_REQUEST, 'task', "" ) );
$id = intval( mosGetParam( $_REQUEST, 'id', 0 ) );
$catid = intval(mosGetParam( $_REQUEST, 'catid', 0 ) );
$bids = mosGetParam($_REQUEST, 'bid', array(0));
$Itemid = mosGetParam($_REQUEST, 'itemid', 0);

// paginations
$intro    =  $realestatemanager_configuration['page']['items']; // page length

if ($intro) 
 {
  $paginations = 1;
  $limit    = intval( mosGetParam( $_REQUEST, 'limit', $intro ) );
  $GLOBALS['limit'] = $limit;
 
  $limitstart = intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );
  
  $GLOBALS['limitstart'] = $limitstart;

  $total    = 0;
  $LIMIT = 'LIMIT '.$limitstart.','.$limit;
 }
else 
{
  $paginations = 0;
  $LIMIT    = '';
}

 $session =& JFactory::getSession();
 $session->set("array",$paginations);


if($realestatemanager_configuration['debug'] == '1'){
  echo "Task: ".$task . "<br />";
  print_r($_REQUEST);
  echo "<hr /><br />";
}

// for 1.6
if ( isset($_REQUEST['view']) ) $view = mosGetParam( $_REQUEST, 'view', '' ) ;
if ( (!isset($task) OR $task == '' ) AND  isset($view)  ) $task = $view;


switch ($task)
{
	case 'get_councils':
		getCouncils($_REQUEST['id_district']);
		break;
	case 'get_parish':
		getParish($_REQUEST['id_council']);
		break;
	case 'get_councils_admin':
		getCouncilsAdmin($_REQUEST['id_district']);
		break;
	case 'get_parish_admin':
		getParishAdmin($_REQUEST['id_council']);
		break;
		
  case 'secret_image':
    secretImage(); 
    break;

	case 'show_search':
    showSearchHouses( $option, $catid, $option );
    break;
	
	case 'search':
    searchHouses( $option, $catid, $option );
    break;

	case 'view':
    	showItemREM( $id, $catid );
    	break;

	case 'review':
    reviewHouse( $option );
    break;
	
	case 'showCategory':
	case 'showcategory':
  
    //if no category is selected show default action
    if ( $catid ) 
    {
      showCategory( $catid );
    } 
    else
    {
      $menu = new mosMenu( $database );
      $menu->load( $GLOBALS['Itemid'] );
      $params = new mosParameters( $menu->params );
      $single_category_id = ''; // for 1.6 
      $single_category_id = $params->get('single_category') ;
      if ( $single_category_id > 0 )
          $catid = $single_category_id;

      showCategory( $catid );
    }
	break;

	case 'rent_request':
		showRentRequest( $option, $bids );
	break;
	
	case 'save_rent_request':
		saveRentRequest( $option, $bids );
	break;

	case 'buying_request':
		saveBuyingRequest( $option, $bids );
	break;
	
	case 'mdownload':
		mydownload($id);
	break;

	case 'downitsf':
		downloaditself($id);
	break;	
	default:
		listCategories($catid);
	break;
	}

function getCouncils($id_district){
	if(!isset($id_district) || $id_district == "all"){
		echo "<option value=\"all\">"._REALESTATE_MANAGER_LABEL_ALL."</option>";
	}
	else {
		global $database;
		$query = "SELECT id, designacao FROM   #__councils where distrito_id = ".$id_district;
		$database->setQuery($query);
		$temp = $database->loadObjectList();
		$councils = "<option value=\"all\">"._REALESTATE_MANAGER_LABEL_ALL."</option>";
		foreach($temp as $value){
			$councils .= "<option value=\"".$value->id."\">".$value->designacao."</option>";
		}
		echo $councils;
	}
}

function getParish($id_council){
	if(!isset($id_council) || $id_council == "all"){
		echo "<option value=\"all\">"._REALESTATE_MANAGER_LABEL_ALL_F."</option>";
	}
	else {
		global $database;
		$query = "SELECT id, designacao FROM   #__parish where concelho_id = ".$id_council;
		$database->setQuery($query);
		$temp = $database->loadObjectList();
		$parish = "<option value=\"all\">"._REALESTATE_MANAGER_LABEL_ALL_F."</option>";
		foreach($temp as $value){
			$parish .= "<option value=\"".$value->id."\">".$value->designacao."</option>";
		}
		echo $parish;
	}
}

function getCouncilsAdmin($id_district){
	if(!isset($id_district) || $id_district == "0"){
		echo "<option value=\"0\">"._REALESTATE_MANAGER_ADMIN_PLEASE_SEL."</option>";
	}
	else {
		global $database;
		$query = "SELECT id, designacao FROM   #__councils where distrito_id = ".$id_district;
		$database->setQuery($query);
		$temp = $database->loadObjectList();
		$councils = "<option value=\"0\">"._REALESTATE_MANAGER_ADMIN_PLEASE_SEL."</option>";
		foreach($temp as $value){
			$councils .= "<option value=\"".$value->id."\">".$value->designacao."</option>";
		}
		echo $councils;
	}
}

function getParishAdmin($id_council){
	if(!isset($id_council) || $id_council == "0"){
		echo "<option value=\"0\">"._REALESTATE_MANAGER_ADMIN_PLEASE_SEL."</option>";
	}
	else {
		global $database;
		$query = "SELECT id, designacao FROM   #__parish where concelho_id = ".$id_council;
		$database->setQuery($query);
		$temp = $database->loadObjectList();
		$parish = "<option value=\"0\">"._REALESTATE_MANAGER_ADMIN_PLEASE_SEL."</option>";
		foreach($temp as $value){
			$parish .= "<option value=\"".$value->id."\">".$value->designacao."</option>";
		}
		echo $parish;
	}
}

function saveRentRequest($option, $bids){
	
  global $mainframe, $database, $my, $Itemid, $acl;
  global $realestatemanager_configuration, $mosConfig_mailfrom;
  
  $pathway =  sefRelToAbs('index.php?option=' . $option .
      '&amp;task=rent_request&amp;Itemid=' . $Itemid);
  //$mainframe->appendPathWay(_REALESTATE_MANAGER_TITLE,$pathway);

  if( !($realestatemanager_configuration['rentstatus']['show'])  ||
    !checkAccess_REM( $realestatemanager_configuration['rentrequest']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl))
  {
                           
    echo _REALESTATE_MANAGER_NOT_AUTHORIZED;
    return;
  }
  
  $help = array();
    $rent_request = new mosRealEstateManager_rent_request($database); 
    $post = JRequest::get('post',JREQUEST_ALLOWHTML);
    if (!$rent_request->bind($post)) {
      echo "<script> alert('".$rent_request->getError()."'); window.history.go(-1); </script>\n";
      exit ();
    }

    $rent_request->rent_request = date("Y-m-d H:i:s");
    $rent_request->fk_houseid = intval($_REQUEST["houseid"]);  
  
    if($rent_request->rent_from >$rent_request->rent_until){
      echo "<script> alert('".
      $rent_request->rent_from.
      " is more than ".$rent_request->rent_until.
      "'); window.history.go(-1); </script>\n";
      exit ();
    }
    $data  = &JFactory::getDBO();
    $query = "SELECT * FROM #__rem_houses where id= ".$rent_request->fk_houseid ;
    $data->setQuery($query);
    $houseid = $data->loadObjectList();
    $query   = "SELECT * FROM #__rem_rent where fk_houseid= ".
         $houseid[0]->id." AND rent_return IS NULL" ;//изменить fk_houseid 
    $data->setQuery($query);
    $rents   = $data->loadObjectList();


    if(isset($rents[0])){ 
      for ($e = 0, $m = count($rents); $e < $m;$e++){
        $rents[$e]->rent_from= substr($rents[$e]->rent_from, 0, 10);
        $rents[$e]->rent_until= substr($rents[$e]->rent_until, 0, 10);
  //cheking the rent  
        
        if(($rent_request->rent_from >=$rents[$e]->rent_from && $rent_request->rent_from <=$rents[$e]->rent_until)||
          ($rent_request->rent_until >= $rents[$e]->rent_from && $rent_request->rent_until <=$rents[$e]->rent_until)||
          ($rent_request->rent_from<=$rents[$e]->rent_from && $rent_request->rent_until>=$rents[$e]->rent_until) )
        {
          echo "<script> alert('Sorry this object is already rent out from ".$rents[$e]->rent_from." to ".$rents[$e]->rent_until."'); window.history.go(-1); </script>\n";
            exit ();
        }
      }
    }

  
    if (!$rent_request->check()) {
      echo "<script> alert('".$rent_request->getError()."'); window.history.go(-1); </script>\n";
      exit ();
    }

    if (!$rent_request->store()) {
      echo "<script> alert('".$rent_request->getError()."'); window.history.go(-1); </script>\n";
      exit ();
    }
  
        
    $rent_request->checkin();
    array_push($help, $rent_request);
  

  
  $currentcat = NULL;
  // Parameters
  $menu = new mosMenu( $database );
  $menu->load( $Itemid );
  $params = new mosParameters( $menu->params );
      $app = JFactory::getApplication();
    $menu1 = $app->getMenu();
    $menu_name = $menu1->getItem($Itemid)->title ;
    $params->def( 'header', $menu_name );
  $params->def( 'pageclass_sfx', '' );
  //
  $params->def( 'show_search', '1' );
  $params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );

  $currentcat->descrip = _REALESTATE_MANAGER_LABEL_RENT_REQUEST_THANKS;
  
  // page image
  $currentcat->img = "./components/com_realestatemanager/images/rem_logo.png";

  $currentcat->header = $params->get( 'header' );
  
  // used to show table rows in alternating colours
  $tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );

	HTML_realestatemanager :: showRentRequestThanks($params, $currentcat);
	
}

function saveBuyingRequest( $option, $bids ){
	global $mainframe, $database, $my, $Itemid, $acl;
	global $realestatemanager_configuration, $mosConfig_mailfrom;

  if( !($realestatemanager_configuration['buystatus']['show'])  ||
    !checkAccess_REM( $realestatemanager_configuration['buyrequest']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl))
  {
                           
		echo _REALESTATE_MANAGER_NOT_AUTHORIZED;
		return;
  }
  
	$buying_request = new mosRealEstateManager_buying_request($database);
	$post = JRequest::get('post',JREQUEST_ALLOWHTML);
	if (!$buying_request->bind($post)) {
			echo $buying_request->getError();
			exit ();
		}
	$buying_request->buying_request = date("Y-m-d H:i:s");
	$buying_request->fk_houseid = $bids[0];
	if (!$buying_request->store()) {
			echo "error:".$buying_request->getError();
// 			exit ();
		}
	$currentcat = NULL;
	// Parameters
  $app = JFactory::getApplication();
  $menu1 = $app->getMenu();
  if ( $menu1->getItem($Itemid) )
    $menu_name = $menu1->getItem($Itemid)->title ;
  else $menu_name = '';
  
  // Parameters
  $menu = new JTableMenu( $database );
	$menu->load( $Itemid );
	$params = new mosParameters( $menu->params );
	$params->def( 'header', $menu_name );
	$params->def( 'pageclass_sfx', '' );
	//
	$params->def( 'show_search', '1' );
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );

	$currentcat->descrip = _REALESTATE_MANAGER_LABEL_BUYING_REQUEST_THANKS;

	// page image
	$currentcat->img = "./components/com_realestatemanager/images/rem_logo.png";

	$currentcat->header = $params->get( 'header' );
 
	HTML_realestatemanager :: showRentRequestThanks($params, $currentcat);
}

function showRentRequest($option,$bid)
{	
	///sprint_r($bid);exit;
	
	global $mainframe, $database, $my, $Itemid, $acl;
	global $realestatemanager_configuration;

  $pathway =  sefRelToAbs('index.php?option=' . $option .
      '&amp;task=rent_request&amp;Itemid=' . $Itemid);
	
  if( !($realestatemanager_configuration['rentstatus']['show'])  ||
		!checkAccess_REM( $realestatemanager_configuration['rentrequest']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl))
  {
    echo _REALESTATE_MANAGER_NOT_AUTHORIZED;
    return;
  }
	
		
	$bids = implode(',', $bid);
	
	// getting all houses for this category
	$query = "SELECT * FROM #__rem_houses"
		. "\nWHERE id IN (" .  $bids . ") ORDER BY catid, ordering";
	$database->setQuery( $query );
	$houses = $database->loadObjectList();
	
	//$houses
	$currentcat = NULL;
	// Parameters
	$menu = new mosMenu( $database );
	$menu->load( $Itemid );
	$params = new mosParameters( $menu->params );
	$params->def( 'header', _REALESTATE_MANAGER_DESC_TITLE );
	//$params->def( 'header', $menu->name );
	$params->def( 'pageclass_sfx', '' );
	$params->def( 'show_rentstatus', 1 );
	$params->def( 'show_rentrequest', 1 );
	$params->def( 'rent_save', 1); 
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );


	// page description
	$currentcat->descrip = _REALESTATE_MANAGER_DESC_RENT;
	
	// page image
	$currentcat->img = './components/com_realestatemanager/images/rem_logo.png';
	$currentcat->align = 'right';

	$currentcat->header = $params->get( 'header' );
	//$currentcat->header = $currentcat->header . ": " . $category->title;
	
	// used to show table rows in alternating colours
	$tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );

	

//	HTML_realestatemanager :: showRentRequest($houses, $currentcat, $params, $tabclass, $catid, $sub_categories,is_exist_subcategory_houses($catid) );
	HTML_realestatemanager :: showRentRequest($houses, $currentcat, $params, $tabclass, $catid, $sub_categories,false);
}


/**
 * comments for registered users
 */
function reviewHouse()
{

	global $mainframe, $database, $my, $Itemid, $acl, $realestatemanager_configuration, $mosConfig_absolute_path, $catid;
	global $mosConfig_mailfrom,$session;
	

	if(!($realestatemanager_configuration['reviews']['show'])  || !checkAccess_REM($realestatemanager_configuration['reviews']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl)) 
        {
		echo _REALESTATE_MANAGER_NOT_AUTHORIZED;
	 	return;
	}	

	
        $review = new mosRealEstateManager_review($database);

	$review->date = date("Y-m-d H:i:s");
	$review->getReviewFrom( $my->id );

	$post = JRequest::get('post',JREQUEST_ALLOWHTML);
	if (!$review->bind($post)) {
		echo "<script> alert('".$house->getError()."'); window.history.go(-1); </script>\n";
		exit ();
	}
	
	if (!$review->check()) {
		echo "<script> alert('".$house->getError()."'); window.history.go(-1); </script>\n";
		exit ();
	}
	if (!$review->store()) {
		echo "<script> alert('".$house->getError()."'); window.history.go(-1); </script>\n";
		exit ();
	}


	$menu =new mosMenu($database);
	$menu->load( $Itemid );
	$params = new mosParameters( $menu->params );
	//showing the original entries
	mosRedirect("index.php?option=com_realestatemanager&task=view&catid=".$_POST['catid']."&id=$review->fk_houseid&Itemid=$Itemid");


  	if(($realestatemanager_configuration['suggest_added_email']['show']) && trim($realestatemanager_configuration['suggest_email']['address']) != "" )
	{
		$params->def( 'show_email', 1 );

		if (checkAccess_REM($realestatemanager_configuration['suggest_added_email']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl)) 
    {
			$params->def( 'show_input_email', 1);
		}
	}

	if ($params->get('show_input_email')) {
	    $mail_to = explode(",",$realestatemanager_configuration['suggest_email']['address']);

		$t = _REALESTATE_MANAGER_LABEL_SUGGESTION_TITLE;
		$c = _REALESTATE_MANAGER_LABEL_SUGGESTION_COMMENT;

    mosMail($mosConfig_mailfrom, $user->user_name,$mail_to, 
      'New house suggestion added',
      'User '. $user->user_name .' has added a house suggestion <br /><br />' 
      .$t.': "'.$title.'" <br /> '
      .$c.': '.$comment. '<br /><br />'
      .' Please log in and check.', true);
	}

	//***********   end add send mail for admin**********
    HTML_realestatemanager :: showRentRequestThanks($params, $currentcat);
	//showing the original entries
//	if ($_REQUEST['where'] == 1) mosRedirect("?option=com_realestatemanager&Itemid=".$_REQUEST['Itemid']." ");
//	if ($_REQUEST['where'] == 2) mosRedirect("?option=com_realestatemanager&task=showCategory&catid=".$_REQUEST['catid']."&Itemid=".$_REQUEST['Itemid']." ");
}
//*******************   end add for suggestion   ********************


//this function check - is exist houses in this folder and folders under this category 
function is_exist_curr_and_subcategory_houses($catid) {
		global $database, $my; 

    $s = getWhereUsergroupsCondition ("cc"); 

		$query = "SELECT *, COUNT(a.id) AS numlinks FROM #__rem_main_categories AS cc" 
      . "\n  JOIN #__rem_categories AS hc ON hc.idcat = cc.id"
			. "\n  JOIN #__rem_houses AS a ON a.id = hc.iditem" 
			. "\n WHERE a.published='1' AND a.approved='1' AND section='com_realestatemanager' AND cc.id='$catid' AND cc.published='1' AND ($s) " 
			. "\n GROUP BY cc.id" 
			. "\n ORDER BY cc.ordering"; 
		$database->setQuery( $query );
   
		$categories = $database->loadObjectList();
		if( count($categories) != 0 ) return true;

		$query = "SELECT id " 
			. "FROM #__rem_main_categories AS cc " 
			. " WHERE section='com_realestatemanager' AND parent_id='$catid' AND published='1' AND ($s) "; 
		$database->setQuery( $query ); 
		$categories = $database->loadObjectList();
 
		if( count($categories) == 0 ) return false;

		foreach($categories as $k) {
			if( is_exist_curr_and_subcategory_houses($k->id) ) return true;
		}
		return false; 
}//end function

//*****************************************************************************

//this function check - is exist folders under this category 
function is_exist_subcategory_houses($catid) {
		global $database, $my; 

    $s = getWhereUsergroupsCondition ("cc"); 
    
		$query = "SELECT *, COUNT(a.id) AS numlinks FROM #__rem_main_categories AS cc" 
      . "\n  JOIN #__rem_categories AS hc ON hc.idcat = cc.id"
			. "\n  JOIN #__rem_houses AS a ON a.id = hc.iditem" 
			. "\n WHERE a.published='1' AND a.approved='1' AND section='com_realestatemanager' AND parent_id='$catid' AND cc.published='1' AND ($s) " 
			. "\n GROUP BY cc.id" 
			. "\n ORDER BY cc.ordering"; 
        
		$database->setQuery( $query );

		$categories = $database->loadObjectList();
		if( count($categories) != 0 ) return true;

		$query = "SELECT id " 
			. "FROM #__rem_main_categories AS cc " 
			. " WHERE section='com_realestatemanager' AND parent_id='$catid' AND published='1' AND ($s) "; 
		$database->setQuery( $query ); 
		$categories = $database->loadObjectList();
 
		if( count($categories) == 0 ) return false;

		foreach($categories as $k) {
			if( is_exist_subcategory_houses($k->id) ) return true;
		}
		return false; 
}//end function


/**
 * This function is used to show a list of all houses
 */
function listCategories( $catid ) 
{
//echo $catid ; exit;

	global $mainframe, $database, $my, $acl;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid, $realestatemanager_configuration;

/////////////////////////////////////////////////////////////

  $s = getWhereUsergroupsCondition ("c");
  
   $query = "SELECT h.*,c.id, c.parent_id, c.title, c.image,COUNT(hc.iditem) as houses,
            '1' as display" .
    " \n FROM  #__rem_main_categories as c ".
    " \n LEFT JOIN #__rem_categories AS hc ON hc.idcat=c.id " .
    " \n LEFT JOIN #__rem_houses AS h ON h.id=hc.iditem " .
    "  \n WHERE c.section='com_realestatemanager' 
            AND c.published=1 AND ({$s})
      \n GROUP BY c.id
      \n ORDER BY c.parent_id DESC, c.ordering ";

     
 $database->setQuery( $query ); 
 $cat_all = $database->loadObjectList();
/*print_r($database);
print_r($cat_all);
exit;*/
  
    foreach($cat_all as $tmp=>$cat_item){
        foreach($cat_all as $cat_item2){
            if($cat_item->id== $cat_item2->parent_id)
                $cat_all[$tmp]->houses += $cat_item2->houses;
        }
    }
    $cat_all_temp = array();
    foreach($cat_all as $tmp=>$cat_item){
    
      if($cat_all[$tmp]->houses > 0 ) $cat_all_temp[] = $cat_item;
    }
    $cat_all = $cat_all_temp;  
////////////////////////////////////////////////////////////


	$currentcat = NULL;
  $app = JFactory::getApplication();
  $menu1 = $app->getMenu();
  if ( $menu1->getItem($Itemid) )
    $menu_name = $menu1->getItem($Itemid)->title ;
  else $menu_name = '';
  
	// Parameters
	$menu = new JTableMenu( $database );
	$menu->load( $Itemid );
	$params = new mosParameters( $menu->params );
	$params->def( 'header', $menu_name );
	$params->def( 'pageclass_sfx', '' );
	$params->def( 'show_search', '1' );
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );

	// page header
	$currentcat->header = $params->get( 'header' );
	//add for show in category picture
	if($realestatemanager_configuration['cat_pic']['show']) $params->def( 'show_cat_pic', 1 );

	// page description
	$currentcat->descrip = _REALESTATE_MANAGER_DESC;

	// used to show table rows in alternating colours
	$tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );

	HTML_realestatemanager::showCategories($params, $cat_all, $catid, $tabclass, $currentcat);
}

function constructPathway($cat){
    global $mainframe, $database, $option, $Itemid,$mosConfig_absolute_path;

    $app = JFactory::getApplication();
    $path_way = $app->getPathway() ;

    $query = "SELECT * FROM #__rem_main_categories WHERE section = 'com_realestatemanager' AND published = 1";
    $database->setQuery($query);
    $rows = $database->loadObjectlist('id');
    if ($cat!= NULL)$pid = $cat->id;  //need check
    $pathway = array();
    $pathway_name = array();
    while($pid != 0){

      $cat = @$rows[$pid];
      $pathway[] =  sefRelToAbs('index.php?option=' . $option . '&task=showCategory&catid=' . @$cat->id . '&Itemid=' . $Itemid);
      $pathway_name[] =  @$cat->title;
      $pid = @$cat->parent_id;
    }
    $pathway = array_reverse($pathway);
    $pathway_name = array_reverse($pathway_name);

    for($i=0,$n=count($pathway);$i<$n;$i++){
      $path_way->addItem($pathway_name[$i],$pathway[$i] );
//echo $pathway[$i] ."::";
    }
//exit;
}

/**
 * This function is used to show a list of all houses
 */

//get current user groups
function getUserGroups(){
  $my=&JFactory::getUser();
  $acl =& JFactory::getACL();
  $usergroups = $acl->get_group_parents($my->gid,'ARO','NORECURSE');
  if($usergroups) $usergroups=','.implode(',',$usergroups); else $usergroups='';
  return '-2,'.$my->gid.$usergroups;
}

function showCategory( $catid )
{

	global $mainframe, $database, $acl, $my;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid, $realestatemanager_configuration;
  global $mosConfig_list_limit,$limit, $total, $limitstart ;

  //getting the current category informations
  $database->setQuery("SELECT * FROM #__rem_main_categories WHERE id='$catid'");
  $category = $database->loadObjectList();
  if(isset($category[0])) $category=$category[0];
  else {
    echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE;
    return;
  }
  
  if($category->params=='') $category->params='-2';
  if(!checkAccess_REM( $category->params,'NORECURSE', userGID_REM($my->id), $acl)) {
            echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE ;
           return;
  }
  //sorting

  
  $item_session = & JFactory::getSession();
  $sort_arr = $item_session->get('rem_housesort','');
  if(is_array($sort_arr)){
      $tmp1=mosGetParam($_POST,'order_direction');
			if($tmp1!=''){
        $sort_arr['order_direction']=$tmp1;
      }
      $tmp1=mosGetParam($_POST,'order_field');
			if($tmp1!=''){
        $sort_arr['order_field']=$tmp1;
      }
      $item_session->set('rem_housesort',$sort_arr);
	}
  else{
      $sort_arr = array();
			$sort_arr['order_field'] = 'htitle';
			$sort_arr['order_direction'] = 'asc';
			$item_session->set('rem_housesort',$sort_arr);
  }
  if($sort_arr['order_field'] == "price")
      $sort_string = "CAST( ".$sort_arr['order_field']." AS SIGNED)"." ".$sort_arr['order_direction'];
  else $sort_string = $sort_arr['order_field'] . " " .$sort_arr['order_direction'];

  //getting groups of user
  $s = getWhereUsergroupsCondition('c');

  $query = "SELECT COUNT(DISTINCT h.id)
       \nFROM #__rem_houses AS h"
    . "\nLEFT JOIN #__rem_categories AS hc ON hc.iditem=h.id"
    . "\nLEFT JOIN #__rem_main_categories AS c ON c.id=hc.idcat"
    . "\nWHERE c.id = '$catid' AND h.published='1' AND h.approved='1' AND c.published='1' AND ($s)";
    
  $database->setQuery( $query );
  $total = $database->loadResult();
  
  $pageNav = new JPagination( $total, $limitstart, $limit ); // for J 1.6

    // getting all houses for this category
  $query = "SELECT h.id, h.hits,h.hlocation, h.htitle, hc.idcat AS catid, c.name AS category, h.fk_rentid, h.price,h.priceunit, h.year,h.link, h.image_link, h.listing_type
       \nFROM #__rem_houses AS h"
    . "\nLEFT JOIN #__rem_categories AS hc ON hc.iditem=h.id"
    . "\nLEFT JOIN #__rem_main_categories AS c ON c.id=hc.idcat"
    . "\nWHERE hc.idcat = '$catid' AND h.published='1' AND h.approved='1' "
    . "\nAND c.published='1' AND ($s)"
    . "\nGROUP BY h.id"
    . "\nORDER BY ".$sort_string
    . "\nLIMIT $pageNav->limitstart,$pageNav->limit;";
  $database->setQuery( $query );

  $houses = $database->loadObjectList();
  //print_r($database);
/////////////////////////////////////////////////////////////

   $query = "SELECT h.*,c.id, c.parent_id, c.title, c.image,COUNT(hc.iditem) as houses,
            '1' as display" .
    " \n FROM  #__rem_main_categories as c ".
    " \n LEFT JOIN #__rem_categories AS hc ON hc.idcat=c.id " .
    " \n LEFT JOIN #__rem_houses AS h ON h.id=hc.iditem " .
    "  \n WHERE c.section='com_realestatemanager' 
            AND c.published=1 AND ({$s})
      \n GROUP BY c.id
      \n ORDER BY c.parent_id DESC, c.ordering ";
    
 $database->setQuery( $query ); 
 $cat_all = $database->loadObjectList();



//    for ($i = 0; $i < count($cat_all); $i++) {
//     if (!is_exist_curr_and_subcategory_houses($cat_all[$i]->id)){
//         $cat_all[$i]->display = 0;
//     }
//   }
    foreach($cat_all as $tmp=>$cat_item){
        foreach($cat_all as $cat_item2){
            if($cat_item->id== $cat_item2->parent_id)
                $cat_all[$tmp]->houses += $cat_item2->houses;
        }
    }
    $cat_all_temp = array();
    foreach($cat_all as $tmp=>$cat_item){
    
      if($cat_all[$tmp]->houses > 0 ) $cat_all_temp[] = $cat_item;
    }
    $cat_all = $cat_all_temp;  
////////////////////////////////////////////////////////////
	

	$currentcat = NULL;
	// Parameters
	$menu = new JTableMenu( $database );//for 1.6

  $app = JFactory::getApplication();
  $menu1 = $app->getMenu();
  //print_r($menu1);exit;
  if ( $menu1->getItem($Itemid) )
    $menu_name = $menu1->getItem($Itemid)->title ;
  else $menu_name = '';

	$menu->load( $Itemid );
	$params = new mosParameters( $menu->params );
	$params->def( 'header', $menu_name );// for 1.6
	$params->def( 'pageclass_sfx', '' );
	$params->def( 'category_name', $category->title );
	$params->def( 'show_search', '1' );
	

	constructPathway($category);
  //$mainframe->appendPathWay($category->title);
  $params->def('sort_arr_order_direction', $sort_arr['order_direction']);
  $params->def('sort_arr_order_field', $sort_arr['order_field']);

	//add for show in category picture
	if( $realestatemanager_configuration['cat_pic']['show']) $params->def( 'show_cat_pic', 1 );

	$params->def( 'show_rating', 1 );
	
	$params->def( 'hits', 1 );
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );

	$currentcat->descrip = $category->description;
	// page image
	$currentcat->img = null;
	$path = $mosConfig_live_site .'/images/stories/';
// 	if ($category->image != null && count($category->image) > 0) {
// 		$currentcat->img = $path . $category->image;
// 		$currentcat->align = $category->image_position;
// 	}

	$currentcat->header = $params->get('header');
	$currentcat->header = $currentcat->header . ": " . $category->title;

	// used to show table rows in alternating colours
	$tabclass = array('sectiontableentry1', 'sectiontableentry2');
	
  $params->def('view_type',$realestatemanager_configuration['view_type']);
  
  HTML_realestatemanager::displayHouses($houses, $currentcat, $params, $tabclass, $catid, $cat_all,is_exist_subcategory_houses($catid),$pageNav);
  
}

function showItemREM($id, $catid)
{
	global $mainframe, $database, $my, $acl, $option ;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid, $realestatemanager_configuration;
 
  $database->setQuery("SELECT id FROM #__rem_houses where id=$id ");
  $trueid=$database->loadResultArray();
  if(!in_array(intval($id),$trueid)){
    echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE;
    return;
  }
 
	//add to path category name
	//getting the current category informations
	$query = "SELECT * FROM #__rem_main_categories WHERE id='$catid'";   
	$database->setQuery( $query );	
	$category = $database->loadObjectList();
  if(isset($category[0])) $category = $category[0];
  else {
      echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE;
      return;
      }
  constructPathway($category);
  $pathway =  sefRelToAbs('index.php?option=' . $option . 
        '&task=showCategory&catid=' . $category->id . '&Itemid=' . $Itemid);
//   $pathway_name =  "house"  ;
//   $mainframe->appendPathWay($pathway_name,$pathway);
//   $mainframe->appendPathWay(" ");

	//Record the hit
	$sql="UPDATE #__rem_houses SET hits = hits + 1 WHERE id = ". $id ."";
	$database->setQuery( $sql );
	$database->query();

	//load the house
	$house = new mosRealEstateManager( $database );
	$house->load($id);
	
	
	
	$query = "SELECT c.title AS category_title
      FROM #__rem_categories AS hc 
      LEFT JOIN #__rem_main_categories AS c ON hc.idcat = c.id
	  WHERE hc.iditem = ".$id;
	  
	$database->setQuery( $query );
	$result = $database->loadObjectList();
	$house->category_title = $result[0]->category_title;

	$query = "SELECT designacao FROM #__districts AS di WHERE di.id = ".$house->district;
	$database->setQuery( $query );
	$result = $database->loadObjectList();
	$house->district_txt = $result[0]->designacao;
	
	$query = "SELECT designacao FROM #__councils AS co WHERE co.id = ".$house->council;
	$database->setQuery( $query );
	$result = $database->loadObjectList();
	$house->council_txt = $result[0]->designacao;
	
	$query = "SELECT designacao FROM #__parish AS pa WHERE pa.id = ".$house->parish;
	$database->setQuery( $query );
	$result = $database->loadObjectList();
	$house->parish_txt = $result[0]->designacao;
		
	
  $house->setOwnerName();
  $access = $house->getAccess_REM();
  if(!checkAccess_REM( $access,'RECURSE', userGID_REM($my->id), $acl)) {
    echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE;
    return;
  }
  if($house->owneremail!=$my->email){
    if($house->published==0){
       echo _REALESTATE_MANAGER_ERROR_HOUSE_NOT_PUBLISHED;
       return;
    }
    if($house->approved==0){
       echo _REALESTATE_MANAGER_ERROR_HOUSE_NOT_APPROVED;
       return;
    }
  }
/////////////////////////////////////////////////////////////////////////////////////

	$listing_type['0'] = '';
  $listing_type['foreclosure'] = _REALESTATE_MANAGER_OPTION_FORECLOSURE;
	$listing_type['house for rent'] = _REALESTATE_MANAGER_OPTION_HOUSE_FOR_RENT;
	$listing_type['room for rent'] = _REALESTATE_MANAGER_OPTION_ROOM_FOR_RENT;
	$listing_type['for sale'] =_REALESTATE_MANAGER_OPTION_FOR_SALE;
	$listing_type['new home'] = _REALESTATE_MANAGER_OPTION_NEW_HOME;
	$listing_type['sublet'] = _REALESTATE_MANAGER_OPTION_SUBLET;
	$house->listing_type = $listing_type[$house->listing_type];

	//cоздание списка "тип цены"
	$test['0'] = '';
	$test['negotiable'] =_REALESTATE_MANAGER_OPTION_NEGOTIABLE;
	$test['starting'] =_REALESTATE_MANAGER_OPTION_STARTING;
	$house->price_type = $test[$house->price_type];

	//cоздание списка "статус сделки"
  $listing_status_type['0'] = '';
	$listing_status_type['active'] =_REALESTATE_MANAGER_OPTION_ACTIVE;
	$listing_status_type['offer'] =_REALESTATE_MANAGER_OPTION_OFFER;
	$listing_status_type['contract'] =_REALESTATE_MANAGER_OPTION_CONTRACT;
	$listing_status_type['closed'] =_REALESTATE_MANAGER_OPTION_CLOSED;
	$listing_status_type['withdrawn'] =_REALESTATE_MANAGER_OPTION_WITHDRAWN;
	$house->listing_status=$listing_status_type[$house->listing_status];
	
	// <-- SOFIA
	$property_type['0'] = '';	
	$property_type['townhouse'] = _REALESTATE_MANAGER_OPTION_TOWNHOUSE;
	$property_type['apartment'] = _REALESTATE_MANAGER_OPTION_APARTMENT;
	$property_type['warehouse'] = _REALESTATE_MANAGER_OPTION_WAREHOUSE;
	$property_type['office'] = _REALESTATE_MANAGER_OPTION_OFFICE;
	$property_type['garage'] = _REALESTATE_MANAGER_OPTION_GARAGE;
	$property_type['store'] = _REALESTATE_MANAGER_OPTION_STORE;
	$property_type['houseind'] = _REALESTATE_MANAGER_OPTION_IND_HOUSE;
	$property_type['housegem'] = _REALESTATE_MANAGER_OPTION_HOUSE_GEM;
	$property_type['housegav'] = _REALESTATE_MANAGER_OPTION_HOUSE_GAV;
	$property_type['houseband'] = _REALESTATE_MANAGER_OPTION_HAOUSE_BAND;
	$property_type['parking'] = _REALESTATE_MANAGER_OPTION_PARKING;
	$property_type['pavillion'] = _REALESTATE_MANAGER_OPTION_PAVILLION;
	$property_type['building'] = _REALESTATE_MANAGER_OPTION_BUILDING;
	$property_type['farm'] = _REALESTATE_MANAGER_OPTION_FARM;
	$property_type['smallfarm'] = _REALESTATE_MANAGER_OPTION_SMALLFARM;
	$property_type['rest'] = _REALESTATE_MANAGER_OPTION_REST;
	$property_type['land'] = _REALESTATE_MANAGER_OPTION_LAND;
	$house->property_type=$property_type[$house->property_type];
	
	$typology['0'] = '';
	$typology['t0'] = "T0";
	$typology['t0+1'] = "T0+1";
	$typology['t1'] = "T1";
	$typology['t1+1'] = "T1+1";
	$typology['t2'] = "T2";
	$typology['t2+1'] = "T2+1";
	$typology['t3'] = "T3";
	$typology['t3+1'] = "T3+1";
	$typology['t4'] = "T4";
	$typology['t4+1'] = "T4+1";
	$typology['>=t5'] = ">=T5";
	$typology['sem'] = 'Outros';
	$house->typology=$typology[$house->typology];
	// -->
	
	//cоздание списка "класс провайдера"
  $provider_class['0'] = '';
	$provider_class['agent']=_REALESTATE_MANAGER_OPTION_AGENT;
	$provider_class['aggregator']=_REALESTATE_MANAGER_OPTION_AGGREGATOR;
	$provider_class['broker']=_REALESTATE_MANAGER_OPTION_BROKER;
	$provider_class['franchisor']=_REALESTATE_MANAGER_OPTION_FRANCHISOR;
	$provider_class['homebuilder']=_REALESTATE_MANAGER_OPTION_HOMEBUILDER;
	$provider_class['publisher']=_REALESTATE_MANAGER_OPTION_PUBLISHER;
	$house->provider_class=$provider_class[$house->provider_class];
	//cоздание списка "районирование"
  $zoning['0'] = '';
	$zoning['agricultural']=_REALESTATE_MANAGER_OPTION_AGRICULTURAL;
	$zoning['commercial']=_REALESTATE_MANAGER_OPTION_COMMERCIAL;
	$zoning['industrial']=_REALESTATE_MANAGER_OPTION_INDUSTRIAL;
	$zoning['recreational']=_REALESTATE_MANAGER_OPTION_RECREATIONAL;
	$zoning['residential']=_REALESTATE_MANAGER_OPTION_RESIDENTIAL;
	$zoning['unincorporated']=_REALESTATE_MANAGER_OPTION_UNINCORPORATED;
	$house->zoning=$zoning[$house->zoning];
	//cоздание списка "style"
  $style['0'] = '';
	$style['Cape Cod']=_REALESTATE_MANAGER_OPTION_CAPE_COD;
	$style['Colonial']=_REALESTATE_MANAGER_OPTION_COLONIAL;
	$style['Craftsman']=_REALESTATE_MANAGER_OPTION_CRAFTSMAN;
	$style['Gothic']=_REALESTATE_MANAGER_OPTION_GOTHIC;
	$style['Prairie']=_REALESTATE_MANAGER_OPTION_PRAIRIE;
	$style['Ranch']=_REALESTATE_MANAGER_OPTION_RANCH2;
	$style['Split Level']=_REALESTATE_MANAGER_OPTION_SPLIT_LEVEL;
	$style['Tudor']=_REALESTATE_MANAGER_OPTION_TUDOR;
	$style['Victorian Queen Anne']=_REALESTATE_MANAGER_OPTION_VICTORIAN_QUEEN_ANNE;
	$house->style=$style[$house->style];

/////////////////////////////////////////////////////////////////////////////////////
	


$app = JFactory::getApplication();
  $menu1 = $app->getMenu();
  if ( $menu1->getItem($Itemid) )
    $menu_name = $menu1->getItem($Itemid)->title ;
  else $menu_name = '';
  // --

  // Parameters
  //$menu = new mosMenu( $database );
  $menu = new JTableMenu( $database ); // for 1.6
	
	// Parameters
	$menu = new mosMenu( $database );
	$menu->load( $Itemid );
	$params = new mosParameters( $menu->params );
	$params->def( 'header', $menu_name );//for 1.6
	$params->def( 'pageclass_sfx', '' );
  if ( !isset($my->id) ) { //for 1.6  
    $my->id = 0;
  }
	if( $realestatemanager_configuration['rentstatus']['show'] ){
		$params->def( 'show_rentstatus', 1 );
		if (checkAccess_REM( $realestatemanager_configuration['rentrequest']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl)) {
			$params->def( 'show_rentrequest', 1);
		}
	}

	if( $realestatemanager_configuration['buystatus']['show'] ){
		$params->def( 'show_buystatus', 1 );
		if (checkAccess_REM( $realestatemanager_configuration['buyrequest']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl)) {
			$params->def( 'show_buyrequest', 1);
		}
	}
	
	if( $realestatemanager_configuration['reviews']['show'] ){
		$params->def( 'show_reviews', 1 );
		if (checkAccess_REM($realestatemanager_configuration['reviews']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl)) {
			$params->def( 'show_inputreviews', 1);
		}
	}	
	
	if( $realestatemanager_configuration['edocs']['show'] ){
		$params->def( 'show_edocstatus', 1 );
		if (checkAccess_REM($realestatemanager_configuration['edocs']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl)) {
			$params->def( 'show_edocsrequest', 1);//+18.01
				//+18.01
					}
		} 

	if( $realestatemanager_configuration['price']['show']){
		$params->def( 'show_pricestatus', 1 );
			$params->def( 'show_pricerequest', 1);//+18.01
		}
		$params->def( 'show_location', 1 );
	  $params->def( 'show_locationtab_registrationlevel', 1);//+18.01
		$params->def( 'show_reviews_tab', 1 );
		$params->def( 'show_reviewstab_registrationlevel', 1);//+18.01
    $params->def( 'show_contacts_line', 1 );
    $params->def('show_contacts_registrationlevel', 1);//+18.01
	  $params->def( 'pageclass_sfx', '' );
	  $params->def( 'item_description', 1 );
	  $params->def( 'show_edoc', $realestatemanager_configuration['edocs']['show']);
	  $params->def( 'show_price', $realestatemanager_configuration['price']['show']);
	  $params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );
	
	// page header
	$currentcat->header = $params->get( 'header' );
	$currentcat->header = $currentcat->header . $house->htitle;
	
	$query = "select main_img from #__rem_photos WHERE fk_houseid=$house->id";
	$database->setQuery( $query );
	$house_photos = $database->loadObjectList();
	// show the house

  $params->def('viewdescription', "{loadposition com_realestatemanager_view_house_description}");

	HTML_realestatemanager::displayHouse( $house, $tabclass, $params, $currentcat, $ratinglist, $house_photos, $id, $catid );
  
}

function showSearchHouses($options, $catid, $option)
{
	global $mainframe, $database, $my;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid;
	$currentcat = NULL;
	// Parameters
	$menu = new mosMenu( $database );
	$menu->load( $Itemid );
	$params = new mosParameters( $menu->params );
  $app = JFactory::getApplication();
  $menu1 = $app->getMenu();
  if ( $menu1->getItem($Itemid) )
    $menu_name = $menu1->getItem($Itemid)->title ;
  else $menu_name = '';
	$params->def( 'header', $menu_name );
	$params->def( 'pageclass_sfx', '' );
	//
	$params->def( 'show_search', '1' );
	$params->def( 'back_button', $mainframe->getCfg( 'back_button' ) );

  $pathway =  sefRelToAbs('index.php?option=' . $option .
      '&amp;task=show_search&amp;Itemid=' . $Itemid);
  $pathway_name =  _REALESTATE_MANAGER_LABEL_SEARCH ;
  //$mainframe->appendPathWay($pathway_name,$pathway);
  
	$currentcat->descrip = " ";
  $currentcat->align = 'right';
	
	// page image
	$currentcat->img = "./components/com_realestatemanager/images/rem_logo.png";


	$currentcat->header = $params->get( 'header' );
	$currentcat->header = $currentcat->header . ": " . _REALESTATE_MANAGER_LABEL_SEARCH;
	
	// used to show table rows in alternating colours
	$tabclass = array( 'sectiontableentry1', 'sectiontableentry2' );

	$categories[] = mosHTML :: makeOption('0', 'Search category');

	$clist = com_house_categoryTreeList(0,'',true,$categories);
  
  $year[] = mosHTML :: makeOption(' ', _REALESTATE_MANAGER_SHOW_SEARCH_FROM);
  $year_to[] = mosHTML :: makeOption(' ', _REALESTATE_MANAGER_SHOW_SEARCH_TO);
  for($i=date('Y');$i>=1900;$i--)
  {
    $year[] = mosHTML :: makeOption($i, $i);
    $year_to[] = mosHTML :: makeOption($i, $i);
  }
  $yearlist = mosHTML :: selectList($year, 'yearfrom', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', 0);
  $yearlistto = mosHTML :: selectList($year_to, 'yearto', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', 0);
  // show the House
  $params->def('yearlist',$yearlist);
  $params->def('yearlistto',$yearlistto);
  
    //price 
  $db =& JFactory::getDBO();
  $query = "SELECT price  FROM   #__rem_houses ";
  $database->setQuery($query);
  $prices = $database->loadResultArray();
  
  rsort($prices,SORT_NUMERIC);
  $max_price = $prices[0];


  $price[] = mosHTML :: makeOption(' ', _REALESTATE_MANAGER_SHOW_SEARCH_FROM);
  $price_to[] = mosHTML :: makeOption(' ', _REALESTATE_MANAGER_SHOW_SEARCH_TO);

  for( $i=0; $i<=$max_price+10000; $i=$i+10000){
  $price[] = mosHTML :: makeOption($i, $i);
  $price_to[] = mosHTML :: makeOption($i, $i);
  }

  $pricelist = mosHTML :: selectList($price, 'pricefrom', 'class="inputbox" size="1"', 'value', 'text', 0);
  $params->def('pricefrom',$pricelist);
  $pricelistto = mosHTML :: selectList($price_to, 'priceto', 'class="inputbox" size="1"', 'value', 'text', 0);
  $params->def('priceto',$pricelistto);
  
  
  
  //Select list for house type
  $listing_type[] = mosHtml::makeOption('all',_REALESTATE_MANAGER_LABEL_ALL);
  $listing_type[] = mosHtml::makeOption("foreclosure",_REALESTATE_MANAGER_OPTION_FORECLOSURE);
  $listing_type[] = mosHtml::makeOption("house for rent",_REALESTATE_MANAGER_OPTION_HOUSE_FOR_RENT);
  $listing_type[] = mosHtml::makeOption('room for rent',_REALESTATE_MANAGER_OPTION_ROOM_FOR_RENT);
  $listing_type[] = mosHtml::makeOption('for sale',_REALESTATE_MANAGER_OPTION_FOR_SALE);
  $listing_type[] = mosHtml::makeOption('new home',_REALESTATE_MANAGER_OPTION_NEW_HOME);
  $listing_type[] = mosHtml::makeOption("sublet",_REALESTATE_MANAGER_OPTION_SUBLET);
  $house_type_list = mosHTML :: selectList($listing_type, 'listing_type', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', '');
  $params->def('house_type_list',$house_type_list);
  
  //Select list for house price type
  $price_type[] = mosHtml::makeOption('all',_REALESTATE_MANAGER_LABEL_ALL);
  $price_type[] = mosHtml::makeOption("negotiable",_REALESTATE_MANAGER_OPTION_NEGOTIABLE);
  $price_type[] = mosHtml::makeOption("starting",_REALESTATE_MANAGER_OPTION_STARTING);
  $house_price_type = mosHTML :: selectList($price_type, 'price_type', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', '');
  $params->def('house_price_type',$house_price_type);

  
  //Select list for house listing status type
  $listing_status_type[] = mosHtml::makeOption('all',_REALESTATE_MANAGER_LABEL_ALL);
  $listing_status_type[] = mosHtml::makeOption("active",_REALESTATE_MANAGER_OPTION_ACTIVE);
  $listing_status_type[] = mosHtml::makeOption("offer",_REALESTATE_MANAGER_OPTION_OFFER);
  $listing_status_type[] = mosHtml::makeOption("contract",_REALESTATE_MANAGER_OPTION_CONTRACT);
  $listing_status_type[] = mosHtml::makeOption("closed",_REALESTATE_MANAGER_OPTION_CLOSED);
  $listing_status_type[] = mosHtml::makeOption("withdrawn",_REALESTATE_MANAGER_OPTION_WITHDRAWN);
  $listing_status_type = mosHTML :: selectList($listing_status_type, 'listing_status', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', '');
  $params->def('listing_status_type',$listing_status_type);  
  
  // <-- SOFIA
  //Select list for house listing property type
  $property_type[] = mosHtml::makeOption('all',_REALESTATE_MANAGER_LABEL_ALL);
  $property_type[] = mosHtml::makeOption("townhouse",_REALESTATE_MANAGER_OPTION_TOWNHOUSE);
  $property_type[] = mosHtml::makeOption("apartment",_REALESTATE_MANAGER_OPTION_APARTMENT);
  $property_type[] = mosHtml::makeOption("warehouse",_REALESTATE_MANAGER_OPTION_WAREHOUSE);
  $property_type[] = mosHtml::makeOption("office",_REALESTATE_MANAGER_OPTION_OFFICE);
  $property_type[] = mosHtml::makeOption("garage",_REALESTATE_MANAGER_OPTION_GARAGE);
  $property_type[] = mosHtml::makeOption("store",_REALESTATE_MANAGER_OPTION_STORE);
  $property_type[] = mosHtml::makeOption("houseind",_REALESTATE_MANAGER_OPTION_IND_HOUSE);
  $property_type[] = mosHtml::makeOption("housegem",_REALESTATE_MANAGER_OPTION_HOUSE_GEM);
  $property_type[] = mosHtml::makeOption("housegav",_REALESTATE_MANAGER_OPTION_HOUSE_GAV);
  $property_type[] = mosHtml::makeOption("houseband",_REALESTATE_MANAGER_OPTION_HAOUSE_BAND);
  $property_type[] = mosHtml::makeOption("parking",_REALESTATE_MANAGER_OPTION_PARKING);
  $property_type[] = mosHtml::makeOption("pavillion",_REALESTATE_MANAGER_OPTION_PAVILLION);
  $property_type[] = mosHtml::makeOption("building",_REALESTATE_MANAGER_OPTION_BUILDING);
  $property_type[] = mosHtml::makeOption("farm",_REALESTATE_MANAGER_OPTION_FARM);
  $property_type[] = mosHtml::makeOption("smallfarm",_REALESTATE_MANAGER_OPTION_SMALLFARM);
  $property_type[] = mosHtml::makeOption("rest",_REALESTATE_MANAGER_OPTION_REST);
  $property_type[] = mosHtml::makeOption("land",_REALESTATE_MANAGER_OPTION_LAND);
  $property_type = mosHTML :: selectList($property_type, 'property_ownership', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', '');
  $params->def('property_type',$property_type);  
	
	$typology[] = mosHtml::makeOption('all',_REALESTATE_MANAGER_LABEL_ALL);
	$typology[] = mosHtml::makeOption("t0", "T0");
	$typology[] = mosHtml::makeOption("t0+1", "T0+1");
	$typology[] = mosHtml::makeOption("t1", "T1");
	$typology[] = mosHtml::makeOption("t1+1", "T1+1");
	$typology[] = mosHtml::makeOption("t2", "T2");
	$typology[] = mosHtml::makeOption("t2+1", "T2+1");
	$typology[] = mosHtml::makeOption("t3", "T3");
	$typology[] = mosHtml::makeOption("t3+1", "T3+1");
	$typology[] = mosHtml::makeOption("t4", "T4");
	$typology[] = mosHtml::makeOption("t4+1", "T4+1");
	$typology[] = mosHtml::makeOption(">=t5", ">=T5");
	$typology[] = mosHtml::makeOption("sem", "Outros");
	$typology = mosHTML :: selectList($typology, 'typology', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', '');
	$params->def('typology',$typology);  
	// -->

  //Select list for house listing status type
  $provider_class[] = mosHtml::makeOption('all',_REALESTATE_MANAGER_LABEL_ALL);
  $provider_class[] = mosHtml::makeOption("agent",_REALESTATE_MANAGER_OPTION_AGENT);
  $provider_class[] = mosHtml::makeOption("aggregator",_REALESTATE_MANAGER_OPTION_AGGREGATOR);
  $provider_class[] = mosHtml::makeOption("broker",_REALESTATE_MANAGER_OPTION_BROKER);
  $provider_class[] = mosHtml::makeOption("franchisor",_REALESTATE_MANAGER_OPTION_FRANCHISOR);
  $provider_class[] = mosHtml::makeOption("homebuilder",_REALESTATE_MANAGER_OPTION_HOMEBUILDER);
  $provider_class[] = mosHtml::makeOption("publisher",_REALESTATE_MANAGER_OPTION_PUBLISHER);
  $provider_class = mosHTML :: selectList($provider_class, 'provider_class', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', '');
  $params->def('provider_class',$provider_class);  


  //Select list for house area
  $zoning[] = mosHtml::makeOption('all',_REALESTATE_MANAGER_LABEL_ALL);
  $zoning[] = mosHtml::makeOption("agricultural",_REALESTATE_MANAGER_OPTION_AGRICULTURAL);
  $zoning[] = mosHtml::makeOption("commercial",_REALESTATE_MANAGER_OPTION_COMMERCIAL);
  $zoning[] = mosHtml::makeOption("industrial",_REALESTATE_MANAGER_OPTION_INDUSTRIAL);
  $zoning[] = mosHtml::makeOption("recreational",_REALESTATE_MANAGER_OPTION_RECREATIONAL);
  $zoning[] = mosHtml::makeOption("residential",_REALESTATE_MANAGER_OPTION_RESIDENTIAL);
  $zoning[] = mosHtml::makeOption("unincorporated",_REALESTATE_MANAGER_OPTION_UNINCORPORATED);
  $zoning = mosHTML :: selectList($zoning, 'zoning', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', '');
  $params->def('zoning',$zoning);  

  
  //Select list for house style
  $style[] = mosHtml::makeOption('all',_REALESTATE_MANAGER_LABEL_ALL);
  $style[] = mosHtml::makeOption("Cape Cod",_REALESTATE_MANAGER_OPTION_CAPE_COD);
  $style[] = mosHtml::makeOption("Colonial",_REALESTATE_MANAGER_OPTION_COLONIAL);
  $style[] = mosHtml::makeOption("Craftsman",_REALESTATE_MANAGER_OPTION_CRAFTSMAN);
  $style[] = mosHtml::makeOption("Gothic",_REALESTATE_MANAGER_OPTION_GOTHIC);
  $style[] = mosHtml::makeOption("Prairie",_REALESTATE_MANAGER_OPTION_PRAIRIE);
  $style[] = mosHtml::makeOption("Ranch",_REALESTATE_MANAGER_OPTION_RANCH2);
  $style[] = mosHtml::makeOption("Split Level",_REALESTATE_MANAGER_OPTION_SPLIT_LEVEL);
  $style[] = mosHtml::makeOption("Tudor",_REALESTATE_MANAGER_OPTION_TUDOR);
  $style[] = mosHtml::makeOption("Victorian Queen Anne",_REALESTATE_MANAGER_OPTION_VICTORIAN_QUEEN_ANNE);
  $style = mosHTML :: selectList($style, 'style', 'class="inputbox" size="1" style="width: 140px"', 'value', 'text', '');
  $params->def('style',$style); 

	// show the House
	HTML_realestatemanager::showSearchHouses( $params, $currentcat, $clist , $option);

}


function searchHouses($options, $catid, $option,$ownername=''){

	global $mainframe, $database, $my, $acl, $limitstart, $limit;
	global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
	global $cur_template, $Itemid, $realestatemanager_configuration;

  //get current user groups
  $s = getWhereUsergroupsCondition ("c"); 
  $session = &JFactory::getSession();
  if($ownername==''){
    $pathway =  sefRelToAbs('index.php?option=' . $option .
        '&amp;task=show_search&amp;Itemid=' . $Itemid);
    $pathway_name =  _REALESTATE_MANAGER_LABEL_SEARCH ;
    //$mainframe->appendPathWay($pathway_name,$pathway);
  }

  if(array_key_exists("searchtext",$_REQUEST)){	
  	$search = mosGetParam( $_REQUEST, 'searchtext', '' );
    $search = addslashes($search); 
    $session->set("poisk",$search);	
  }	

  $poisk_search = $session->get("poisk","");

	$where              = array();
	$address            = " ";
	$title              = " ";
	$broker             = " ";
	$feature            = " ";
	$description        = " ";
	$area		            = " ";
	$model 	            = " ";
	$agent 	            = " ";
	$zoning             = " ";
	$Rent               = " ";
	$RentSQL            = " ";
	$RentSQL_JOIN_1	    = " ";
	$RentSQL_JOIN_2     = " ";
	$RentSQL_rent_until = " ";
  $houseid            = " ";
  $country            = " ";
  $region             = " ";
  $city               = " ";
 
	if(isset($_REQUEST['exactly']) && $_REQUEST['exactly']=="on"){
    $exactly=$poisk_search;
	}
  else{
    $exactly="%$poisk_search%";
  }
  
  if(isset($_REQUEST['yearfrom']) && (intval($_REQUEST['yearfrom'])>1900) && (intval($_REQUEST['yearto'])>1900) && isset($_REQUEST['yearto'])){
      $year=" (b.year BETWEEN ".intval($_REQUEST['yearfrom'])." and ".intval($_REQUEST['yearto']).") ";
  }
  elseif(isset($_REQUEST['yearfrom'])&& (intval($_REQUEST['yearfrom'])>1900)) 
  {
    $year=" b.year >= ".intval($_REQUEST['yearfrom'])." ";
  }
  elseif(isset($_REQUEST['yearto'])&& (intval($_REQUEST['yearto'])>1900))
  {
    $year=" b.year <= ".intval($_REQUEST['yearto'])." ";
  }

  //sorting
  $item_session = & JFactory::getSession();
  $sort_arr = $item_session->get('rem_housesort','');
  if(is_array($sort_arr)){
      $tmp1=mosGetParam($_POST,'order_direction');
			if($tmp1!=''){
        $sort_arr['order_direction']=$tmp1;
      }
      $tmp1=mosGetParam($_POST,'order_field');
			if($tmp1!=''){
        $sort_arr['order_field']=$tmp1;
      }
      $item_session->set('rem_housesort',$sort_arr);
	}
  else{
      $sort_arr = array();
			$sort_arr['order_field'] = 'htitle';
			$sort_arr['order_direction'] = 'asc';
			$item_session->set('rem_housesort',$sort_arr);
  }
  if($sort_arr['order_field'] == "price")
      $sort_string = "CAST( ".$sort_arr['order_field']." AS SIGNED)"." ".$sort_arr['order_direction'];
  else $sort_string = $sort_arr['order_field'] . " " .$sort_arr['order_direction'];  //end sortering

  
  
  $is_add_or = false;
  $add_or_value  = "  ";
  
if($poisk_search!=''){
	if(isset($_GET['address']) && $_GET['address']=="on"){
      $address = " ";
      if($is_add_or) $address = " or " ;
      $is_add_or = true;
      $address .=" ( LOWER(b.hlocation) LIKE '%$poisk_search%' ";
      $address .="OR LOWER(b.hcountry) LIKE '%$poisk_search%' ";
      $address .="OR LOWER(b.hregion) LIKE '%$poisk_search%' ";
      $address .="OR LOWER(b.hcity) LIKE '%$poisk_search%' ) ";
	}
	if(isset($_GET['title']) && $_GET['title']=="on"){
      $title = " ";
      if($is_add_or) $title = " or " ;
      $is_add_or = true;
      $title .=" LOWER(b.htitle) LIKE '%$poisk_search%' ";
	}
	if(isset($_GET['broker']) && $_GET['broker']=="on"){
      $broker = " ";
      if($is_add_or) $broker = " or " ;
      $is_add_or = true;
      $broker .=" LOWER(b.broker) LIKE '%$poisk_search%' ";
	}

	if(isset($_GET['feature']) && $_GET['feature']="on"){
      $feature = " ";
      if($is_add_or) $feature = " or " ;
      $is_add_or = true;
      $feature .=" LOWER(b.feature) LIKE '%$poisk_search%' ";
	}
	
	if(isset($_GET['description']) && $_GET['description']=="on"){
      $description = " ";
      if($is_add_or) $description = " or " ;
      $is_add_or = true;
      $description .=" LOWER(b.description) LIKE '%$poisk_search%' ";
	}
	
	if(isset($_GET['area']) && $_GET['area']=="on"){
      $area = " ";
      if($is_add_or) $area = " or " ;
      $is_add_or = true;
      $area .=" LOWER(b.area) LIKE '%$poisk_search%' ";
	}
	
	if(isset($_GET['model']) && $_GET['model']=="on"){	
      $model = " ";
      if($is_add_or) $model = " or " ;
      $is_add_or = true;
      $model .=" LOWER(b.model) LIKE '%$poisk_search%' ";
	}

	if(isset($_GET['agent']) && $_GET['agent']=="on"){	
      $agent = " ";
      if($is_add_or) $agent = " or " ;
      $is_add_or = true;
      $agent .=" LOWER(b.agent) LIKE '%$poisk_search%' ";
	}  

  if(isset($_REQUEST['country']) && $_REQUEST['country']=="on"){
      $country = " ";
      if($is_add_or) $country = " or " ;
      $is_add_or = true;
      $country .= "LOWER(b.hcountry) LIKE '$exactly' ";
  }

  if(isset($_REQUEST['region']) && $_REQUEST['region']=="on"){
      $region = " ";
      if($is_add_or) $region = " or " ;
      $is_add_or = true;
      $region .= "LOWER(b.hregion) LIKE '$exactly' ";
  }

  if(isset($_REQUEST['city']) && $_REQUEST['city']=="on"){
      $city = " ";
      if($is_add_or) $city = " or " ;
      $is_add_or = true;
      $city .= "LOWER(b.hcity) LIKE '$exactly' ";
  }

}

  $listing_type=mosGetParam( $_REQUEST, 'listing_type', '' );
  $style=mosGetParam( $_REQUEST, 'style', '' );
  $zoning=mosGetParam( $_REQUEST, 'zoning', '' );
  $provider_class=mosGetParam( $_REQUEST, 'provider_class', '' );
  $property_type=mosGetParam( $_REQUEST, 'property_ownership', '' );
  $typology=mosGetParam( $_REQUEST, 'typology', '');	//SOFIA
  $district=mosGetParam( $_REQUEST, 'district', '');	//SOFIA
  $council=mosGetParam( $_REQUEST, 'council', '');	//SOFIA
  $parish=mosGetParam( $_REQUEST, 'parish', '');	//SOFIA
  $listing_status=mosGetParam( $_REQUEST, 'listing_status', '' );
  $price_type=mosGetParam( $_REQUEST, 'price_type', '' );

  if(isset($_REQUEST['houseid'])){
      $where[]= "LOWER(b.houseid) LIKE '%".$_REQUEST['houseid']."%' ";
  }

  if($listing_type!='all' && $listing_type!=''){
      $where[]= " LOWER(b.listing_type)='$listing_type'";
  }

  if($style!='all' && $style!=''){
      $where[]= " LOWER(b.style) LIKE '%$style%'";
  }
  if($zoning!='all' && $zoning!=''){
      $where[]= " LOWER(b.zoning) LIKE '%$zoning%'";
  }
  if($provider_class!='all' && $provider_class!=''){
      $where[]= " LOWER(b.provider_class) LIKE '%$provider_class%'";
  }
  if($property_type!='all' && $property_type!=''){
      $where[]= " LOWER(b.property_type) LIKE '%$property_type%'";
  }
  // <-- SOFIA
  if($typology!='all' && $typology!=''){
	  $where[]= "LOWER(b.typology) = '$typology'";
  }
  if($district!='all' && $district!=''){
	  $where[]= "b.district = '$district'";
  }
  if($council!='all' && $council!=''){
	  $where[]= "b.council = '$council'";
  }
  if($parish!='all' && $parish!=''){
	  $where[]= "b.parish = '$parish'";
  }
  // -->
  if($listing_status!='all' && $listing_status!=''){
      $where[]= " LOWER(b.listing_status) LIKE ='$listing_status'";
  }

  if($price_type!='all' && $price_type!=''){
      $where[]= " LOWER(b.price_type) LIKE ='$price_type'";
  }
  
  
  $pricefrom=intval(mosGetParam( $_REQUEST, 'pricefrom', '' ) );
  $priceto=intval(mosGetParam( $_REQUEST, 'priceto', '' ) );
   //echo $pricefrom,$preceto;
  if($pricefrom>0)
  {
    $where[] = " CAST( b.price AS SIGNED) >= $pricefrom ";
  }
  if($priceto>0)
  {
    $where[] = " CAST( b.price AS SIGNED) <= $priceto ";
  }

  //********owners search
  if(isset($_REQUEST['ownername']) && $_REQUEST['ownername']=="on"){
      $ownername = "$exactly";
  }


  if($ownername!='' && $ownername!='%%'){
    $query="SELECT u.email
            \n FROM #__users AS u
            \n WHERE LOWER(u.name) LIKE '$ownername';";
    $database->setQuery($query);
    $owneremails=$database->loadResultArray();


    $ownername = "";
    if(count($owneremails)){
      foreach($owneremails as $owneremail){
        if(isset($_REQUEST['ownername']) && $_REQUEST['ownername']=="on"){
         //search from frontend

          if($is_add_or) $ownername .= " or " ;
          $is_add_or = true;
          $ownername .= "b.owneremail='$owneremail'";
        }
        else{
          //show owner houses
          $where[]="b.owneremail='$owneremail'";

        }
      }
     } else if(!$is_add_or) {

         echo"<h1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
         ._REALESTATE_MANAGER_LABEL_SEARCH_NOTHING_FOUND."</h1>";
         return;
     }
  }

    //  print_r($_REQUEST['search_date_from']);exit;
  $search_date_from=mosGetParam( $_REQUEST, 'search_date_from', '' );
  $search_date_from = addslashes($search_date_from) ;
  $search_date_until=mosGetParam( $_REQUEST, 'search_date_until', '' );
  $search_date_until = addslashes($search_date_until) ;
  
  if(isset($_REQUEST['search_date_from']) && (trim($_REQUEST['search_date_from'])  ) && trim($_REQUEST['search_date_until']) == ""){ 
      $RentSQL="  ( ( fk_rentid = 0 OR
       b.id NOT IN (select dd.fk_houseid from #__rem_rent AS dd where dd.rent_until > '".
       $search_date_from."' and dd.rent_from < '".
       $search_date_from."' and dd.fk_houseid=b.id ) ) ".
      " AND (listing_type = \"house for rent\" OR 
      listing_type = \"room for rent\" OR 
      listing_type = \"sublet\" ) ) ";
      if($is_add_or) $RentSQL .= " AND " ;
 
      $RentSQL_JOIN_1="\nLEFT JOIN #__rem_rent AS d "; 
      $RentSQL_JOIN_2="\nON d.fk_houseid=b.id ";
  }
  if(isset($_REQUEST['search_date_until']) && (trim($_REQUEST['search_date_until']) ) && trim($_REQUEST['search_date_from']) == "" ){ 
      $RentSQL="  ( ( fk_rentid = 0  OR
       b.id NOT IN (select dd.fk_houseid from #__rem_rent AS dd where dd.rent_from < '".
       $search_date_until."' and dd.rent_until > '".
       $search_date_until."' and dd.fk_houseid=b.id ) ) ".
      " AND (listing_type = \"house for rent\" OR 
      listing_type = \"room for rent\" OR 
      listing_type = \"sublet\" ) ) ";
      if($is_add_or) $RentSQL .= " AND " ;
 
      $RentSQL_JOIN_1="\nLEFT JOIN #__rem_rent AS d "; 
      $RentSQL_JOIN_2="\nON d.fk_houseid=b.id ";
  }
  if(isset($_REQUEST['search_date_until']) && (trim($_REQUEST['search_date_until']) ) 
    && isset($_REQUEST['search_date_from']) && ( trim($_REQUEST['search_date_from'])  ) ){ 
      $RentSQL="  ( ( fk_rentid = 0 OR
       b.id NOT IN (select dd.fk_houseid from #__rem_rent AS dd where  ( dd.rent_until > '".
       $search_date_from."' and dd.rent_from < '".
       $search_date_from."' )   or ".
      " ( dd.rent_from < '".$search_date_until .
      "' and dd.rent_until > '".$search_date_until."' ) or ".
      " ( dd.rent_from > '".
      $search_date_from."' and dd.rent_until < '".
      $search_date_until."' ) ) ) ".
      " AND (listing_type = \"house for rent\" OR 
      listing_type = \"room for rent\" OR 
      listing_type = \"sublet\" ) ) ";
      if($is_add_or) $RentSQL .= " AND " ;

      $RentSQL_JOIN_1="\nLEFT JOIN #__rem_rent AS d "; 
      $RentSQL_JOIN_2="\nON d.fk_houseid=b.id ";
  }

  $RentSQL = $RentSQL.(($is_add_or)?( "( ( ".$address."  " . $title."  ". $broker . "  ".
      $feature."  ".$description. "  ". $area."  ". $model  . "  " .
       $agent."  ".  $houseid ."  ".  $ownername ."  ".  $country ."  ".  $region ."  ".  $city ."  ))"):(" "));
  if(trim($RentSQL) !="" ) array_push($where, $RentSQL );

  if(isset($year))
  {
    array_push($where, $year);
  }
  //select category, to which user has access
  $where[]= " ($s) ";
  $where[]= " c.published = '1' " ;
  //select published and approved houses
  array_push($where, " b.published = '1' " );
  array_push($where, " b.approved = '1' " );
  
  if($catid){
		array_push($where, "c.id=$catid");
	} 

  $query = "SELECT COUNT(DISTINCT b.id)
            FROM #__rem_houses AS b
            LEFT JOIN #__rem_categories AS hc ON b.id=hc.iditem
            LEFT JOIN #__rem_main_categories AS c ON hc.idcat = c.id ".
            $RentSQL_JOIN_1.$RentSQL_JOIN_2.
            ((count($where) ? "\n WHERE ".implode(' AND ', $where) : ""));
	
  $database->setQuery( $query );
  $total = $database->loadResult();
  $pageNav = new JPagination( $total, $limitstart, $limit ); // for J 1.6

	// getting all houses for this category
    $query = "SELECT distinct  b . * , c.title AS category_titel, c.ordering AS category_ordering, 
	  di.designacao as district_txt, co.designacao as council_txt, pa.designacao as parish_txt
      FROM #__rem_houses AS b
      LEFT JOIN #__rem_categories AS hc ON b.id=hc.iditem
      LEFT JOIN #__rem_main_categories AS c ON hc.idcat = c.id
	  LEFT JOIN #__districts AS di ON b.district = di.id 
	  LEFT JOIN #__councils AS co ON b.council = co.id 
	  LEFT JOIN #__parish AS pa ON b.parish = pa.id ".
	  
      $RentSQL_JOIN_1.$RentSQL_JOIN_2. 
      ((count($where) ? "\n WHERE ".implode(' AND ', $where) : "")).
      " GROUP BY b.id ORDER BY $sort_string
        \nLIMIT ".$pageNav->limitstart.",".$pageNav->limit;

	$database->setQuery( $query );
	$houses = $database->loadObjectList();  

// print_r($pageNav);
// 
// print_r($database);
// 
// print_r($houses);
// exit;

	$currentcat = NULL;
	// Parameters
	$menu = new mosMenu($database);
	$menu->load( $Itemid );
	$params = new mosParameters($menu->params);
  $app = JFactory::getApplication();
  $menu1 = $app->getMenu();
  if ( $menu1->getItem($Itemid) )
    $menu_name = $menu1->getItem($Itemid)->title ;
  else $menu_name = '';
	$params->def('header', $menu_name);
	$params->def('pageclass_sfx', '');
	$params->def('category_name', _REALESTATE_MANAGER_LABEL_SEARCH);
	$params->def('search_request', '1');
	$params->def('hits', 1);
	$params->def('show_rating', 1);

  $params->def('sort_arr_order_direction', $sort_arr['order_direction']);
  $params->def('sort_arr_order_field', $sort_arr['order_field']);

  $database->setQuery("SELECT id FROM #__menu WHERE link='index.php?option=com_realestatemanager'");
  if($database->loadResult()!=$Itemid){
    $params->def('wrongitemid','1');
  };

	if( $realestatemanager_configuration['rentstatus']['show'] ){
		$params->def('show_rentstatus', 1);
		if (checkAccess_REM($realestatemanager_configuration['rentrequest']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl)) {
			$params->def( 'show_rentrequest', 1);
		}
	}
	if( $realestatemanager_configuration['buystatus']['show'] ){
		$params->def( 'show_buystatus', 1 );
		if (checkAccess_REM( $realestatemanager_configuration['buyrequest']['registrationlevel'],'NORECURSE', userGID_REM($my->id), $acl)) {
			$params->def( 'show_buyrequest', 1);
		}
	} 
	//add for show in category picture
	if($realestatemanager_configuration['cat_pic']['show']) $params->def('show_cat_pic',1);
	$params->def( 'back_button', $mainframe->getCfg('back_button'));
	$currentcat->descrip = " ";
	$currentcat->align = 'right';
	// page image
	$currentcat->img = "./components/com_realestatemanager/images/rem_logo.png";
	$currentcat->header = $params->get( 'header' );
	$currentcat->header = $currentcat->header . _REALESTATE_MANAGER_LABEL_SEARCH;
	// used to show table rows in alternating colours
	$tabclass = array('sectiontableentry1', 'sectiontableentry2');
	if(isset($houses[0])){	
		HTML_realestatemanager::displayHouses($houses, $currentcat, $params, $tabclass, $catid, null,false,$pageNav);
	}else{
	print_r("<h1 >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"._REALESTATE_MANAGER_LABEL_SEARCH_NOTHING_FOUND." </h1><br><br> ");
	   }
	}

function checkAccess_REM( $accessgroupid, $recurse, $usersgroupid, $acl) {
	
	//parse usergroups
	$tempArr = array();
	$tempArr = explode(',',$accessgroupid);
//	print_r($tempArr);echo ':<br />'; print_r($usersgroupid);
//	echo ':<BR />';
	for($i = 0;$i<count($tempArr);$i++)
	{
	 if($tempArr[$i] == $usersgroupid || $tempArr[$i]==-2){
		return 1;
		}else 
		if($recurse == 'RECURSE'){
			$groupchildren=array();
			$groupchildren=$acl->get_group_children($tempArr[$i], 'ARO', $recurse);
			if(is_array($groupchildren)&& count($groupchildren) > 0) 
				if(in_array($usersgroupid, $groupchildren))
					return 1;
		}
	}
        
	//deny access
  return 0;
}

function userGID_REM($oID){
  	global $database,$ueConfig;
	if($oID > 0) {
		$query ="SELECT gid FROM #__users WHERE id = '".$oID."'";
		$database->setQuery($query);
		$gid = $database->loadResult();
		return $gid;
	}
	else return 0;
}


function com_house_categoryTreeList($id, $action,$is_new, &$options = array())
  {
    global  $database;
    $list = com_house_categoryArray();
    $cat = new mainRealEstateCategories($database);
    $cat->load($id);
  
    $this_treename = '';
    $childs_ids =  Array();
    foreach ($list as $item) {
      if ($item->id == $cat->id || array_key_exists($item->parent_id,$childs_ids) )
      $childs_ids[$item->id] = $item->id;
    }
  
    foreach ($list as $item) {
      if ($this_treename) {
        if ($item->id != $cat->id
          && strpos($item->treename, $this_treename) === false
          && array_key_exists($item->id,$childs_ids) === false) {
          $options[] = mosHTML::makeOption($item->id, $item->treename);
        }
      } else {
        if ($item->id != $cat->id) {
          $options[] = mosHTML::makeOption($item->id, $item->treename);
        } else {
          $this_treename = "$item->treename/";
        }
      }
    }
 
    $parent= null;
    $parent = mosHTML::selectList($options, 'catid',
  'class="inputbox" size="1" style="width: 140px"' , 'value', 'text', $cat->parent_id);
    return $parent;
  }



function com_house_categoryArray()
  {
    global $database,$my,$acl;

    // get a list of the menu items
    $query = "SELECT c.*, c.parent_id AS parent, c.params AS access"
    . "\n FROM #__rem_main_categories c"
    . "\n WHERE section='com_realestatemanager'"
    . "\n AND published <> -2"
    . "\n ORDER BY ordering" ;
    $database->setQuery($query);
    $items = $database->loadObjectList();
    foreach($items as $r=>$cat_item){
     if(!checkAccess_REM( $cat_item->access,'NORECURSE', userGID_REM($my->id), $acl)) {//if have not access then remove item from search
      unset($items[$r]);
     }
    }
    $items=array_values($items);
    // establish the hierarchy of the menu
    $children = array();
    // first pass - collect children
    foreach ($items as $v) {
      $pt = $v->parent;
      $list = @$children[$pt] ? $children[$pt] : array();
      array_push($list, $v);
      $children[$pt] = $list;
    }
    // second pass - get an indent list of the items
    $array = mosTreeRecurse(0, '', array(), $children);
  
    return $array;
  }
